/*
* Copyright (c) 2025 Huawei Device Co., Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including but not limited to the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to provide persons with access to the Software
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGE OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

import React, { useRef, useEffect, useState } from 'react';
import { useStore } from '../../store/store';
import { useNavigate, useLocation } from 'react-router-dom';
import {
  NavigationContainerReact,
  NavigationContentReact,
  NavigationBarReact,
  TabBarContainerReact,
  TabBarContentReact,
  TabBarReact,
  TabBarItemReact,
} from '@hadss/web_adaptive_layout_react';
import { BreakpointManager } from '@hadss/web_adaptive_layout_ui';
import { messageData } from '../../mocks/mockData';
import { MessageItem, TabItem } from '../../types/types';
import './MessageList.css';
import { AvoidArea, AvoidAreaInfo, AvoidAreaType } from '../../common/windowCommon';

const MessageList: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { dispatch } = useStore();
  const breakpointManager = new BreakpointManager();
  const [messageDataList] = useState<MessageItem[]>(messageData);
  const [activeItem, setActiveItem] = useState<MessageItem>({
    id: '11',
    name: '张晓萌',
    message: '好的，我明天过来',
    time: '13:55',
    avatar: require('../../assets/images/touxiang.svg'),
    unread: null,
  });
  const currentPath = useRef<string>(location.pathname);
  const [currentBp, setCurrentBp] = useState<string>('');
  const [mode] = useState<string>('');
  const [currentMode, setCurrentMode] = useState<string>('');
  const [navBarWidth] = useState<number>(570);
  const [selectedColor, setSelectedColor] = useState<string>('rgb(10, 89, 247)');
  const [unselectedColor] = useState<string>('rgba(0, 0, 0, 0.6)');
  const [navigationPageName] = useState<string>('messageList');
  const [navBarWidthRange] = useState<number[]>([260, 570]);
  const [minContentWidth] = useState<number>(340);
  const [navBarPosition] = useState<string>('Start');
  const [navItems] = useState<TabItem[]>([
    { icon: 'xiaoxi', title: '消息', active: true },
    { icon: 'txl', title: '通讯录', active: true },
    { icon: 'sjq', title: '社交圈', active: true },
    { icon: 'my', title: '我的', active: true },
  ]);
  const [topAvoidArea, setTopAvoidArea] = useState(0);
  const [bottomAvoidArea, setBottomAvoidArea] = useState(0);

  const isLgOrXl = ['lg', 'xl'].includes(currentBp);
  const widthTab = isLgOrXl ? '96px' : '100%';
  const [heightTab, setBarHeight] = useState({
    'md': '56px',
    'lg': '100%'
  });

  const goHome = (): void => {
    if (currentMode === 'Split' && location.pathname === '/messageList/detailContainer') {
      navigate(-2);
    } else {
      navigate(-1);
    }
  };

  useEffect(() => {
    currentPath.current = location.pathname;
  }, [location]);

  const handleClickTable = (tab: any): void => {
    if (tab.index === 0) {
      setSelectedColor('rgb(10, 89, 247)');
    } else {
      setSelectedColor('rgba(0, 0, 0, 0.6)');
    }
  };

  const handleMessageClick = (item: MessageItem): void => {
    setActiveItem(item);
    dispatch({ type: 'UPDATE_ITEM', payload: item });
    if (currentPath.current === '/messageList') {
      navigate('/messageList/detailContainer', { state: item });
    }
  };

  const handleAvoidAreaChange = (event: any): void => {
    const data = event.detail as AvoidAreaInfo;
    const areaType = data.type;
    if (areaType === AvoidAreaType.TYPE_SYSTEM) {
      const topAvoidArea = (window as any).webClass?.pxToVp(data.area.topRect.height);
      setTopAvoidArea(topAvoidArea);
    }
    if (areaType === AvoidAreaType.TYPE_NAVIGATION_INDICATOR) {
      const bottomAvoidArea = (window as any).webClass?.pxToVp(data.area.bottomRect.height);
      setBottomAvoidArea(bottomAvoidArea);
      setBarHeight({
        'md': `${56 + bottomAvoidArea}px`,
        'lg': '100%'
      });
    }
  };

  const setAvoidValue = (): void => {
    if ((window as any).webClass) {
      const webClass = (window as any).webClass;
      const topArea = webClass.getAvoidArea(AvoidAreaType.TYPE_SYSTEM) as AvoidArea;
      const bottomArea = webClass.getAvoidArea(AvoidAreaType.TYPE_NAVIGATION_INDICATOR) as AvoidArea;
      const topAvoidArea = webClass.pxToVp(topArea.topRect.height);
      const bottomAvoidArea = webClass.pxToVp(bottomArea.bottomRect.height);
      setTopAvoidArea(topAvoidArea);
      setBottomAvoidArea(bottomAvoidArea);
      setBarHeight({
        'md': `${56 + bottomAvoidArea}px`,
        'lg': '100%'
      });
    }
  };

  const onNavigationModeChange = (mode: string): void => {
    setCurrentMode(mode);
    if (mode === 'Split' && currentPath.current !== '/messageList/detailContainer') {
      navigate('/messageList/detailContainer');
    }
  };

  useEffect(() => {
    dispatch({ type: 'UPDATE_ITEM', payload: activeItem });
    const unsubscribe = breakpointManager.subscribeToBreakpoint((vp: string) => {
      setCurrentBp(vp);
      dispatch({ type: 'UPDATE_CURRENT_BP', payload: vp });
    });
    setAvoidValue();
    window.addEventListener('avoidAreaChange', handleAvoidAreaChange);
    return (): void => {
      if (unsubscribe) {
        unsubscribe();
      }
      window.removeEventListener('avoidAreaChange', handleAvoidAreaChange);
    };
  }, []);

  return (
    <div className='adaptive-layout'>
      <NavigationContainerReact
        mode={mode}
        navigationPageName={navigationPageName}
        navBarWidth={navBarWidth}
        navBarWidthRange={navBarWidthRange as []}
        minContentWidth={minContentWidth}
        navBarPosition={navBarPosition}
        onNavigationModeChange={onNavigationModeChange}
      >
        <NavigationBarReact>
          <TabBarContainerReact>
            <TabBarContentReact>
              <div className='list-container'>
                <div className='container' style={{ paddingTop: `${topAvoidArea}px`, height: `calc(100% - ${topAvoidArea}px)` }}>
                  <div className='title-wrap'>
                    <div className='title-info'>
                      <div className='go-back' onClick={goHome}>
                        <img className='title-img' src={require('../../assets/images/left.png')} />
                      </div>
                      <div className='title-link'>
                        <span className='title'>消息</span>
                      </div>
                    </div>
                    <div className='icon-wrap'>
                      <>
                        <img
                          className='title-img'
                          src={require('../../assets/images/search.png')}
                          alt='搜索'
                        />
                        <img
                          className='title-img'
                          src={require('../../assets/images/add.png')}
                          alt='添加'
                          style={{ marginLeft: '8px' }}
                        />
                      </>
                    </div>
                  </div>
                  <ul className='content message-list'>
                    {messageDataList.map((item) => (
                      <li
                        key={item.id}
                        className={`message-item ${activeItem.id === item.id ? 'item-active' : ''}`}
                        onClick={(): void => handleMessageClick(item)}
                      >
                        <div className='item-list'>
                          <div className='item-img-wrap'>
                            <img
                              className='item-img'
                              src={item.avatar}
                              alt={item.name}
                            />
                            {item.unread && (
                              <div
                                className={`unread-bubble-wrap ${typeof item.unread === 'number' ? 'numerical' : 'dot'}`}
                              >
                                <span className='unread-bubble'>{item.unread}</span>
                              </div>
                            )}
                          </div>
                          <div className='item-content'>
                            <div className='content-main'>{item.name}</div>
                            <div className='content-secondary'>{item.message}</div>
                          </div>
                          <div className='item-time'>{item.time}</div>
                        </div>
                      </li>
                    ))}
                  </ul>
                </div>
              </div>
            </TabBarContentReact>
            <TabBarReact
              width={widthTab}
              height={heightTab}
              bgColor='rgb(241, 243, 245)'
              selectedColor={selectedColor}
              unselectedColor={unselectedColor}
              onTabItemClick={handleClickTable}
            >
              {navItems.map((item, index) => (
                <TabBarItemReact
                  name={index.toString()}
                  key={index}
                >
                  <div className='tab-center' style={{ marginBottom: `${bottomAvoidArea}px` }}>
                    <img
                      className='toolbar-icon'
                      src={require(`../../assets/images/${item.icon}.svg`)}
                      alt={item.title}
                    />
                    <div
                      className={`toolbar-title ${index === 0 ? 'toolbar_info' : ''
                        } ${item.active ? 'active' : ''}`}
                    >
                      {item.title}
                    </div>
                  </div>
                  
                </TabBarItemReact>
              ))}
            </TabBarReact>
          </TabBarContainerReact>
        </NavigationBarReact>
        <NavigationContentReact />
      </NavigationContainerReact>
    </div>
  );
};

export default MessageList;